package model

import (
	"errors"
	"fmt"
	"github.com/imroc/req"
	"net/url"
	"strings"
)

type GiteeBranchesResult struct {
	Name   string `json:"name"`
	Commit struct {
		Sha string `json:"sha"`
		Url string `json:"url"`
	} `json:"commit"`
	Protected     bool   `json:"protected"`
	ProtectionUrl string `json:"protection_url"`
}

type GiteeRepoResult struct {
	ID int `json:"id"`
}

type GiteeCreateWebHookResult struct {
	ID uint `json:"id"`
}

type Gitee struct {
	url         string
	accessToken string
	parse       *url.URL
	search      []string
}

func NewGitee(_url string) (*Gitee, error) {
	_urlParse, err := url.Parse(_url)
	if err != nil {
		return &Gitee{}, err
	}
	search := strings.Split(strings.Replace(_urlParse.Path, ".git", "", -1), "/")
	if len(search) < 3 {
		return &Gitee{}, errors.New("less is short")
	}
	AccessToken, _ := _urlParse.User.Password()
	return &Gitee{url: _url, parse: _urlParse, search: search, accessToken: AccessToken}, nil
}

//获取分支信息
func (m *Gitee) GetBranches() (results []GiteeBranchesResult, err error) {
	err = nil
	NewUrl := "https://gitee.com/api/v5/repos/" + m.search[1] + "/" + m.search[2] + "/branches"
	if m.accessToken != "" {
		NewUrl += "?access_token=" + m.accessToken
	}
	header := req.Header{"Accept": "application/json;charset=UTF-8"}
	r, err := req.Get(NewUrl, header)
	if err != nil {
		return
	}
	if r.Response().StatusCode != 200 {
		err = errors.New(fmt.Sprintf("%v", r))
		return
	}
	err = r.ToJSON(&results)
	if results == nil {
		err = errors.New("请确认该仓库是否有权限！ ")
		return
	}
	if err != nil {
		return
	}
	return
}

//获取仓库信息
func (m *Gitee) GetReposId() (RepId int) {
	RepId = 0
	NewUrl := "https://gitee.com/api/v5/repos/" + m.search[1] + "/" + m.search[2] + ""
	if m.accessToken != "" {
		NewUrl += "?access_token=" + m.accessToken
	}
	header := req.Header{"Accept": "application/json;charset=UTF-8"}
	r, err := req.Get(NewUrl, header)
	if err != nil {
		return
	}
	if r.Response().StatusCode != 200 {
		err = errors.New(fmt.Sprintf("%v", r))
		return
	}
	var results GiteeRepoResult
	err = r.ToJSON(&results)
	if err != nil {
		return
	}
	RepId = results.ID
	return
}

//创建钩子
//https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoHooks
func (m *Gitee) CreateWebHook(url, password string) (results GiteeCreateWebHookResult, err error) {
	NewUrl := "https://gitee.com/api/v5/repos/" + m.search[1] + "/" + m.search[2] + "/hooks"
	if m.accessToken != "" {
		NewUrl += "?access_token=" + m.accessToken
	}
	param := req.Param{
		"url":                   url, //远程HTTP URL
		"encryption_type":       0,   //加密类型: 0: 密码, 1: 签名密钥
		"password":              password,
		"push_events":           "true", //Push代码到仓库
		"merge_requests_events": "true", //合并请求和合并后
	}
	header := req.Header{"Accept": "application/json;charset=UTF-8"}
	r, err := req.Post(NewUrl, header, param)
	if err != nil {
		return
	}
	if r.Response().StatusCode != 201 {
		err = errors.New(fmt.Sprintf("%v", r))
		return
	}
	err = r.ToJSON(&results)
	if err != nil {
		return
	}
	return
}

//删除钩子
func (m *Gitee) DeleteWebHook(id string) (err error) {
	NewUrl := "https://gitee.com/api/v5/repos/" + m.search[1] + "/" + m.search[2] + "/hooks/" + id
	if m.accessToken != "" {
		NewUrl += "?access_token=" + m.accessToken
	}
	header := req.Header{"Accept": "application/json;charset=UTF-8"}
	r, err := req.Delete(NewUrl, header)
	if err != nil {
		return
	}
	if r.Response().StatusCode != 204 {
		err = errors.New(fmt.Sprintf("%v", r))
		return
	}
	return
}
